package com.ygd.encryptiondemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.TextView;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class MainActivity extends AppCompatActivity {

    private PrivateKey mPrivateKey;
    private PublicKey mPublicKey;
    private TextView mShowKeys;
    private byte[] result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        mShowKeys = (TextView) findViewById(R.id.showKey);
    }

    public void generate(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1、获取公钥私钥生成的对象
                try {
                    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

                    //2、初始化,指定密码的长度bit
                    generator.initialize(1024 * 3);

                    //3、获取公钥和私钥
                    KeyPair keyPair = generator.generateKeyPair();

                    //3.1获取私钥
                    //私钥保存好了，
                    mPrivateKey = keyPair.getPrivate();

                    //3.2获取公钥
                    //公钥丢了，可以通过私钥推倒
                    mPublicKey = keyPair.getPublic();

                    //私钥的具体数据，私钥字节数组，保持该数据，文件中，sp
                    //!!!必须进行Base64转换
                    byte[] mPrivateKeyEncoded = mPrivateKey.getEncoded();

                    byte[] mPublicKeyEncoded = mPublicKey.getEncoded();

                    final byte[] privateKeyBase64Encode = Base64.encode(mPrivateKeyEncoded, Base64.DEFAULT);

                    final byte[] publicKeyBase64Encode = Base64.encode(mPublicKeyEncoded, Base64.DEFAULT);

                    //显示到文本框中
                    mShowKeys.post(new Runnable() {
                        @Override
                        public void run() {
                            mShowKeys.setText("私钥是：" + "\n" + new String(privateKeyBase64Encode)
                                    + "公钥是：" + "\n" + publicKeyBase64Encode);
                        }
                    });


                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }

    //使用公钥，秘钥尽心加密界面
    public void encrypt(View view) {
        //使用私钥去加密，使用公钥进行解密
        //举例：
        //阿里巴巴-------->传给千峰，传文件
        //文件加密，私钥加密文件，传给千峰
        //千峰持有公钥，公钥进行解密
        String check = "100000000,123456";
        switch (view.getId()) {
            case R.id.rsaEncrypt:

                try {
                    //1、获取加密引擎
                    Cipher cipher = Cipher.getInstance("RSA");

                    //2、初始化
                    if (mPrivateKey != null) {
                        cipher.init(Cipher.ENCRYPT_MODE, mPrivateKey);
                    }

                    //3、加密
                    byte[] doFinal = cipher.doFinal(check.getBytes());

                    result = Base64.encode(doFinal, Base64.DEFAULT);

                    mShowKeys.setText("RES加密的数据是:" + new String(result));

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                }

                break;

            case R.id.rsaDecrypt:
                try {
                    //1、获取解密引擎
                    Cipher cipher = Cipher.getInstance("RSA");

                    //2、初始化
                    if (mPrivateKey != null) {
                        cipher.init(Cipher.DECRYPT_MODE, mPublicKey);
                    }

                    //3、解密


                    byte[] base64Decode = Base64.decode(result, Base64.DEFAULT);

                    byte[] decyptBytes = cipher.doFinal(base64Decode);

                    mShowKeys.setText("RES解密的数据是:" + new String(decyptBytes));

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                }


                break;
        }
    }


}
